package cn.com.twoke.application.game.mario.core.ecs.world;

import cn.com.twoke.application.game.mario.core.ecs.entity.Entity;
import cn.com.twoke.application.game.mario.core.ecs.entity.EnhancementEntity;
import cn.com.twoke.application.game.mario.core.ecs.system.GameSystem;
import cn.com.twoke.application.game.mario.core.ecs.system.LogicGameSystem;
import cn.com.twoke.application.game.mario.core.ecs.system.PhysicsSystem;
import cn.com.twoke.application.game.mario.core.ecs.system.RenderGameSystem;
import cn.com.twoke.application.game.mario.game.system.TransfersSystem;

import java.util.ArrayList;
import java.util.List;

public class GameWorld {
    private final List<Entity> entities = new ArrayList<>();
    private final List<GameSystem> systems = new ArrayList<>();
    private int nextEntityId = 0;
    private TransfersSystem transfersSystem;

    public Entity createEntity() {
        Entity entity = new EnhancementEntity(transfersSystem, nextEntityId++);
        entities.add(entity);
        return entity;
    }

    public void addSystem(GameSystem system) {
        systems.add(system);
        if (system instanceof TransfersSystem) {
            transfersSystem = (TransfersSystem) system;
        }
    }

    public void update(double delta) {
        for (GameSystem system : systems) {
            if (system instanceof LogicGameSystem) {
                ((LogicGameSystem)system).update(entities, delta);
            }
        }
    }

    public RenderGameSystem getRenderSystem() {
      return (RenderGameSystem) systems.stream().filter(item -> item instanceof RenderGameSystem)
              .findFirst().orElseThrow(() -> new RuntimeException("没有找到可用的渲染系统"));
    }

    public List<Entity> getEntities() {
        return entities;
    }
    
    /**
     * 清理游戏世界资源
     */
    public void cleanup() {
        // 清理实体
        entities.clear();
        
        // 清理系统资源
        for (GameSystem system : systems) {
            if (system instanceof RenderGameSystem) {
                ((RenderGameSystem) system).cleanup();
            }
        }
        
        // 清理纹理缓存
        cn.com.twoke.application.game.mario.game.util.TextureUtils.clearCache();
    }

}